

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class CSocketClientDemo {
	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException{

		Selector selc = Selector.open();  //创建选择器
		SocketChannel sc = SocketChannel.open();
		sc.configureBlocking(false);
        sc.connect(new InetSocketAddress("127.0.0.1",9999));   //指定监听端口

		sc.register(selc, SelectionKey.OP_CONNECT);
		while(true){
			int selcCont = selc.select();
			if(selcCont > 0){
				Set<SelectionKey> set = selc.selectedKeys();
				Iterator<SelectionKey>it = set.iterator();
				while (it.hasNext()){
					SelectionKey sk = it.next();
					SocketChannel scx = (SocketChannel)sk.channel();     //获取sk对应的通道
					if(sk.isConnectable()){
						scx.finishConnect(); //完成连接
						scx.register(selc, SelectionKey.OP_WRITE);
					}else if (sk.isWritable()){
					    StringBuffer sb = new StringBuffer();
						String str = "...";
                        String sendStr = str.getBytes().length+"\r\n"+str;

						ByteBuffer buf = ByteBuffer.wrap(sendStr.getBytes());  //发送数据
						while(buf.hasRemaining()){
							scx.write(buf);
						}

                        sk.cancel();

					}else if(sk.isReadable()){


                    }


				}
				it.remove();
			}

		}

	}

}